package com.ncloud.system.business;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.system.entity.*;
import com.ncloud.system.service.CompanyService;
import com.ncloud.system.service.DepartService;
import com.ncloud.system.service.RoleService;
import com.ncloud.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by shiqiang on 2017/7/31.
 */
@Component
public class RoleBusi {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RoleService roleService;
    @Autowired
    private DepartService departService;
    @Autowired
    private UserService userService;
    @Autowired
    private MenuBusi menuBusi;
    @Autowired
    private CompanyService companyService;
    @Transactional
    public void addRole(Role role){
        if(companyService.getCompanyStateById(role.getCompanyId().intValue()).intValue()>=1){
            throw new UserException(ResultEnum.COMPANY_LOCK);
        }
        /*角色*/
        Long roleId = roleService.insertRole(role);
        /*角色菜单*/
       role.getMenus().stream().forEach(menu -> {
           RoleMenu roleMenu = new RoleMenu();
           roleMenu.setRoleId(roleId);
           roleMenu.setMenuId(menu.getMenuId());
           roleMenu.setUseTag("1");
           roleService.insertRoleMenu(roleMenu);
       });
    }

    @Transactional
    public void modifyRole(Role role){
        if(companyService.getCompanyStateById(role.getCompanyId().intValue()).intValue()>=1){
            throw new UserException(ResultEnum.COMPANY_LOCK);
        }
        /*部门*/
        roleService.updateRole(role);
        /*部门角色*/
        roleService.deleteRoleMenu(role.getRoleId());
        role.getMenus().stream().forEach(menu->{
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenuId(menu.getMenuId());
            roleMenu.setRoleId(role.getRoleId());
            roleMenu.setUseTag("1");
            roleService.insertRoleMenu(roleMenu);
        });
    }

    @Transactional
    public void deleteRole(Long companyId,Long roleId){
        if(companyService.getCompanyStateById(roleId.intValue()).intValue()>=1){
            throw new UserException(ResultEnum.COMPANY_LOCK);
        }
        /*异常校验*/
        List list = departService.getDepartRoleByRole(roleId);
        int accountCount = userService.getRoleUsers(roleId);
        boolean flag = false;
        if(list !=null && list.size()>0){
            flag =true;
        }
        if(accountCount>0){
            flag =true;
        }
        if(flag){
            throw new UserException(ResultEnum.ROLE_DEL_ACCOUNT_PEPART);
        }
         /*部门*/
        roleService.deleteRoleState(roleId);
        /*部门角色*/
        roleService.deleteRoleMenuState(roleId);


    }

    @Transactional(readOnly= true)
    public List<RoleDetail> getRoleInfo(Long userId){
        List<RoleDetail> list = new ArrayList<RoleDetail>();
        //这里根据用户获取用户信息，这里暂时写死
        User user = userService.findByUserId(userId);
         /*部门:如果是系统超级管理员，查询所有，否则查询自己组织*/
        List<Role> roles = null;
        if("1".equals(user.getSuperman())){
            roles = roleService.getRolesByAll();
        }else{
            Long companyId = user.getCompanyId();
            roles = roleService.getRolesByCompanyId(companyId);
        }
        /*部门角色*/
        roles.stream().forEach(role -> {
            RoleDetail roleDetail = new RoleDetail();
            BeanUtils.copyProperties(role, roleDetail);
            List<Menu> menus = roleService.getMenusByRole(role.getRoleId());
            roleDetail.setMenus(menus);
            roleDetail.setMenuCount(menus.size());
            roleDetail.setAccountCount(userService.getRoleUsers(role.getRoleId()));//账户数
            roleDetail.setDepartCount(departService.getDepartRoleByRole(role.getRoleId()).size());
            list.add(roleDetail);
        });
        return list;
    }

    @Transactional(readOnly= true)
    public Role getRoleDetail(Long roleId){
        /*部门*/
        Role role = roleService.getOneRole(roleId);
        //BeanUtils.copyProperties(role, roleDetail);
        /*部门角色*/
        List<Menu> menus = roleService.getMenusByRole(roleId);
        role.setMenus(menus);
        return role;
    }

    @Transactional(readOnly= true)
    public JSONObject getRoleDetailJson(Long roleId){
        JSONObject result = new JSONObject();
        /*部门*/
        Role role = roleService.getOneRole(roleId);
        result = JSON.parseObject(JSON.toJSONString(role));
        /*部门角色*/
        //List<Menu> menus = roleService.getMenusByRole(roleId);
        result.put("menus",menuBusi.getSelectMenusByRole(roleId));
        return result;
    }
}
